package com.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.reggie.dto.DishDto;
import com.reggie.exception.CustomException;
import com.reggie.mapper.DishMapper;
import com.reggie.pojo.Category;
import com.reggie.pojo.Dish;
import com.reggie.pojo.DishFlavor;
import com.reggie.service.CategoryService;
import com.reggie.service.DishFlavorService;
import com.reggie.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Transactional
@Service("dishService")
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private CategoryService categoryService;
    /**
     * 新增菜品 同时 保存口味数据
     * @param dishDto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)      //因为涉及操作多表，所以要开启事务
    public void saveWithFlavor(DishDto dishDto) {
        //保存菜品基本信息,会自动映射相应的字段名保存
        this.save(dishDto);
        //数据保存之后会将数据再回填到对象中，获取菜品ID
        Long dishId = dishDto.getId();//菜品ID
        //菜品口味添加dishID
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors = flavors.stream().peek((item) -> {
            item.setDishId(dishId);
            //    重新转为一个List集合
        }).collect(Collectors.toList());
        //保存菜品口味信息
        dishFlavorService.saveBatch(flavors);
    }

    /**
     * 查询菜品信息和口味信息
     * @param id
     */
    @Override
    public DishDto getByIdWithFlavor(String id) {
        //查询菜品基本信息
        Dish dish = this.getById(id);
        //创建dishDto对象
        DishDto dishDto = new DishDto();
        //赋值给新对象
        BeanUtils.copyProperties(dish, dishDto);
        //获得口味列表
        LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DishFlavor::getDishId, dish.getId());
        List<DishFlavor> dishDtoList = dishFlavorService.list(wrapper);

        //口味列表赋给dishDto对象
        dishDto.setFlavors(dishDtoList);
        return dishDto;
    }

    /**
     * 更新菜品信息包括口味
     * @param dishDto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateWithFlavor(DishDto dishDto) {
        //更新dish表基本信息
        this.updateById(dishDto);
        //清理当前表的对应口味
        LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DishFlavor::getDishId, dishDto.getId());

        dishFlavorService.remove(wrapper);

        //添加当前表的口味数据
        //数据保存之后会将数据再回填到对象中，获取菜品ID
        Long dishId = dishDto.getId();//菜品ID
        //菜品口味添加dishID
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors = flavors.stream().peek((item) -> {
            item.setDishId(dishId);
            //    重新转为一个List集合
        }).collect(Collectors.toList());
        //保存菜品口味信息
        dishFlavorService.saveBatch(flavors);

    }

    /**
     * 删除菜品和口味信息
     * @param ids 菜品id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteWithFlavor(List<Long> ids) {
        //查询菜品状态，确定是否可以删除
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(Dish::getId, ids);
        wrapper.eq(Dish::getStatus, 1);

        int count = this.count(wrapper);
        if (count > 0) {
            //有正在售卖的菜品，不能删除，抛出业务异常
            throw new CustomException("菜品正在售卖中，不能删除！");
        }
        //删除菜品信息
        this.removeByIds(ids);
        //删除菜品的口味信息
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(DishFlavor::getDishId, ids);

        dishFlavorService.remove(queryWrapper);
    }

    @Override
    public List<DishDto> getDishDto(List<Dish> dishList) {
        //处理返回数据
        List<DishDto> dishDtoList = dishList.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            //拷贝公共属性
            BeanUtils.copyProperties(item, dishDto);
            //获取当前菜品的Id
            Long dishId = item.getId();
            //根据Id查询口味对象
            LambdaQueryWrapper<DishFlavor> dishFlavorQueryWrapper = new LambdaQueryWrapper<>();
            dishFlavorQueryWrapper.eq(DishFlavor::getDishId, dishId);
            List<DishFlavor> flavorList = dishFlavorService.list(dishFlavorQueryWrapper);
            if (flavorList != null) {
                //给dto对象的口味属性赋值
                dishDto.setFlavors(flavorList);
            }
            //获取分类Id
            Long categoryId = item.getCategoryId();
            //根据id查询分类名称
            Category category = categoryService.getById(categoryId);
            //增加属性
            dishDto.setCategoryName(category.getName());
            //将改造好的属性返回
            return dishDto;
        }).collect(Collectors.toList());

        return dishDtoList;
    }
}
